<template>
  <div class="bigbox">
    <div class="topbox">
      <el-form
        :model="form"
        ref="form"
        label-position="left"
        label-width="80px"
        onsubmit="return false"
      >
        <el-row :gutter="20">
          <el-col :span="5">
            <el-form-item label="用电企业">
              <FilterSelect2
                v-model="bizOrgNo"
                :optionlist="companyList"
                :valuekey="{ name: 'name', value: 'id' }"
                @changeSelect="companyChange"
              ></FilterSelect2>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="产品">
              <FilterSelect2
                v-model="form.productId"
                :optionlist="productList"
                :valuekey="{ name: 'name', value: 'id' }"
                placeholder="请选择产品"
              ></FilterSelect2>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="年度">
              <el-date-picker
                v-model="form.yearDate"
                type="year"
                placeholder="请选择年度"
                format="yyyy"
                size="small"
                value-format="yyyy"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="9" style="text-align: right">
            <el-form-item>
              <Twobtn @chaxun="chaxun" @chongzhi="chongzhi"></Twobtn>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="bodybox">
      <div class="titlebox">
        <div class="text">单位:万元</div>
        <div style="flex: 1; text-align: right; margin-right: 10px">
          <el-button
            type="primary"
            size="small"
            @click="generateData"
            :disabled="generateDisabled"
          >
            <i class="el-icon-plus">生成</i>
          </el-button>
          <el-button type="primary" size="small" @click="exportTemplate">
            <i class="el-icon-download">导出模版</i>
          </el-button>
          <el-button type="primary" size="small" @click="importData">
            导入月度产值
          </el-button>
          <el-button
            type="primary"
            size="small"
            @click="saveData"
            :disabled="!hasData"
          >
            保存
          </el-button>
        </div>
        <TopTile
          @command="command"
          @daochu="daochu"
          @shuaxin="shuaxin"
        ></TopTile>
      </div>
      <div class="table-content">
        <template>
          <el-table
            v-loading="loading"
            :data="tableData"
            style="width: 100%"
            border
            id="exportTabyong"
            ref="table"
            :size="iissize"
            :header-cell-style="{
              background: '#f5f5f5',
              'text-align': 'center'
            }"
          >
            <template slot="empty">
              <el-empty description="暂无数据"></el-empty>
            </template>
            <el-table-column
              type="index"
              align="center"
              label="序号"
              width="80"
            >
            </el-table-column>
            <el-table-column prop="productName" label="年" min-width="100">
            </el-table-column>
            <el-table-column
              v-for="month in monthColumns"
              :key="month.key"
              :label="month.label"
              :prop="month.key"
              min-width="100"
            >
              <template slot-scope="scope">
                <el-input
                  v-if="scope.row.productName !== '总产值'"
                  v-model="scope.row.monthDataMap[month.key]"
                  placeholder="请输入"
                  size="small"
                  @input="handleNumberInput($event, scope.row, month.key)"
                ></el-input>
                <span v-else>{{
                  scope.row.monthDataMap[month.key] || ''
                }}</span>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </div>
    </div>

    <!-- 导入文件对话框 -->
    <el-dialog
      title="导入月度产值"
      :visible.sync="importDialogVisible"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-upload
        ref="upload"
        :auto-upload="false"
        :on-change="handleFileChange"
        :file-list="fileList"
        accept=".xlsx,.xls"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传xlsx/xls文件</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="importDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmImport">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getCompanyListApi } from '@/api/Configuration-management/index'
import { getProductListApi } from '@/api/energy-consumption/factory-energy/team-allocation'
import {
  getMonthlyCapacityListApi,
  getMonthlyCapacityInitApi,
  saveMonthlyCapacityApi,
  importMonthlyCapacityApi
} from '@/api/energy-consumption/factory-energy/month-capacity-maintenance'
import { exportexcel } from '@/utils/excel'
import FilterSelect2 from '@/components/FilterSelect2/index.vue'
import TopTile from '@/components/TopTitle/index.vue'
import Twobtn from '@/components/Twobtn/index.vue'
import dayjs from 'dayjs'

export default {
  name: 'MonthCapacityMaintenance',
  components: {
    FilterSelect2,
    TopTile,
    Twobtn
  },
  data() {
    return {
      dataList: [],
      enterpriseCode: '',
      id: '',
      bizOrgNo: '',
      dizhi: '',
      form: {
        productId: '',
        yearDate: dayjs().format('YYYY') // 默认今年
      },
      statusList: [],
      address: '',
      isshow: false,
      isheight: 72,
      date: [],
      iissize: 'medium',
      loading: false,
      tableData: [],
      total: 0,
      progress: 1,
      addType: '',
      companyData: {},
      companyList: [],
      productList: [], // 产品列表
      monthColumns: [], // 月份列配置
      generateDisabled: false, // 生成按钮禁用状态
      hasData: false, // 是否有数据
      importDialogVisible: false, // 导入对话框显示状态
      fileList: [], // 文件列表
      currentFile: null // 当前选择的文件
    }
  },

  async mounted() {
    await this.getCompanyList()
    await this.getProductList()
    this.initMonthColumns()
    await this.getdatalist()
  },
  methods: {
    // 初始化月份列
    initMonthColumns() {
      const year = this.form.yearDate || dayjs().format('YYYY')
      this.monthColumns = []
      for (let i = 1; i <= 12; i++) {
        const month = i.toString().padStart(2, '0')
        this.monthColumns.push({
          key: `${year}${month}`,
          label: `${year}${month}`
        })
      }
    },
    async companyChange(val) {
      if (val) {
        localStorage.setItem('companyId', val)
        // 切换企业时重新获取产品列表
        await this.getProductList()
        // 清空产品选择
        this.form.productId = ''
      }
    },
    // 获取用电企业列表
    async getCompanyList() {
      const res = await getCompanyListApi({ companyId: this.bizOrgNo })
      console.log(res)
      this.companyList = res.data.list
      const companyId = +localStorage.getItem('companyId')
      if (companyId && this.companyList.find((i) => i.id == companyId)) {
        this.bizOrgNo = companyId
      } else {
        this.bizOrgNo = this.companyList[0].id
      }
    },
    // 获取产品列表
    async getProductList() {
      try {
        const res = await getProductListApi({
          companyId: this.bizOrgNo
        })
        if (res.code === 200) {
          this.productList = res.data.list || []
        }
      } catch (error) {
        console.error('获取产品列表失败:', error)
        this.productList = []
      }
    },
    // 初始化
    async getchushihua() {
      this.bizOrgNo = this.companyList[0].id
    },
    // 获取数据
    async getdatalist() {
      this.loading = true
      try {
        const res = await getMonthlyCapacityListApi({
          companyId: this.bizOrgNo,
          productId: this.form.productId,
          yearDate: this.form.yearDate
        })
        if (res.code === 200) {
          const list = res.data.list || []
          // 如果只有一条数据且是总产值，则视为空数组
          if (list.length === 1 && list[0].productName === '总产值') {
            this.tableData = []
            this.hasData = false
          } else {
            this.tableData = list
            this.hasData = list.length > 0
          }
          // 更新生成按钮状态：只有一条总产值或空数组时可点击，多条数据时不可点击
          this.generateDisabled =
            this.tableData.length > 1 ||
            (this.tableData.length === 1 &&
              this.tableData[0].productName !== '总产值')
        }
      } catch (error) {
        console.error('获取数据失败:', error)
        this.tableData = []
        this.hasData = false
        this.generateDisabled = false
      }
      this.loading = false
    },
    // 刷新列表
    shuaxin() {
      this.getdatalist('')
      this.$message({
        type: 'success',
        message: '列表刷新成功',
        duration: 2000
      })
    },
    chaxun() {
      this.initMonthColumns() // 重新初始化月份列
      this.getdatalist()
    },
    // 导出
    daochu() {
      exportexcel(
        '/ecm-microservice-biz/ecm/monthly/capacity/set/export',
        {
          companyId: this.bizOrgNo,
          productId: this.form.productId,
          yearDate: this.form.yearDate
        },
        '月度产能维护'
      )
    },
    command(val) {
      if (val === '默认') {
        this.iissize = 'medium'
      } else if (val === '中等') {
        this.iissize = 'small'
      } else {
        this.iissize = 'mini'
      }
    },
    // 生成数据
    async generateData() {
      if (!this.form.yearDate) {
        this.$message.warning('请先选择年度')
        return
      }
      this.generateDisabled = true
      this.loading = true
      try {
        const res = await getMonthlyCapacityInitApi({
          companyId: this.bizOrgNo,
          productId: this.form.productId,
          yearDate: this.form.yearDate
        })
        if (res.code === 200) {
          const list = res.data.list || []
          // 如果只有一条数据且是总产值，则视为空数组
          if (list.length === 1 && list[0].productName === '总产值') {
            this.tableData = []
            this.hasData = false
          } else {
            this.tableData = list
            this.hasData = list.length > 0
          }
          // 更新生成按钮状态：生成后如果有多条数据则不可点击
          this.generateDisabled =
            this.tableData.length > 1 ||
            (this.tableData.length === 1 &&
              this.tableData[0].productName !== '总产值')
          this.$message.success('数据生成成功')
        } else {
          this.$message.error(res.message || '数据生成失败')
        }
      } catch (error) {
        console.error('生成数据失败:', error)
        this.$message.error('数据生成失败')
      }
      this.loading = false
    },
    // 保存数据
    async saveData() {
      if (!this.hasData) {
        this.$message.warning('请先生成数据')
        return
      }
      this.loading = true
      try {
        const data = {
          companyId: this.bizOrgNo,
          yearDate: this.form.yearDate,
          dataList: this.tableData.map((item) => ({
            productId: item.productId,
            productName: item.productName,
            monthDataMap: item.monthDataMap || {}
          }))
        }
        const res = await saveMonthlyCapacityApi(data)
        if (res.code === 200) {
          this.$message.success('保存成功')
          // 保存成功后自动调用查询
          this.getdatalist()
        } else {
          this.$message.error(res.message || '保存失败')
        }
      } catch (error) {
        console.error('保存失败:', error)
        this.$message.error('保存失败')
      }
      this.loading = false
    },
    // 导出模版
    exportTemplate() {
      exportexcel(
        '/ecm-microservice-biz/ecm/monthly/capacity/set/demo',
        {
          companyId: this.bizOrgNo,
          yearDate: this.form.yearDate,
          productId: this.form.productId
        },
        '月度产能维护模版'
      )
    },
    // 导入数据
    importData() {
      this.importDialogVisible = true
      this.fileList = []
      this.currentFile = null
    },
    // 文件选择变化
    handleFileChange(file, fileList) {
      this.currentFile = file.raw
      this.fileList = fileList
    },
    // 确认导入
    async confirmImport() {
      if (!this.currentFile) {
        this.$message.warning('请选择要导入的文件')
        return
      }
      this.loading = true
      try {
        const formData = new FormData()
        formData.append('file', this.currentFile)
        formData.append('companyId', this.bizOrgNo)
        formData.append('yearDate', this.form.yearDate)

        const res = await importMonthlyCapacityApi(formData)
        if (res.code === 200) {
          const list = res.data.list || []
          // 如果只有一条数据且是总产值，则视为空数组
          if (list.length === 1 && list[0].productName === '总产值') {
            this.tableData = []
            this.hasData = false
          } else {
            this.tableData = list
            this.hasData = list.length > 0
          }
          // 更新生成按钮状态
          this.generateDisabled =
            this.tableData.length > 1 ||
            (this.tableData.length === 1 &&
              this.tableData[0].productName !== '总产值')
          this.$message.success('导入成功')
          this.importDialogVisible = false
        } else {
          this.$message.error(res.message || '导入失败')
        }
      } catch (error) {
        console.error('导入失败:', error)
        this.$message.error('导入失败')
      }
      this.loading = false
    },
    async chongzhi() {
      await this.getchushihua()
      this.date = []
      this.enterpriseCode = ''
      this.dataList = []
      this.form.productId = ''
      this.form.yearDate = dayjs().format('YYYY')
      this.initMonthColumns()
      this.getdatalist('')
      // 重新获取产品列表
      await this.getProductList()
    },
    // 处理数字输入
    handleNumberInput(value, row, monthKey) {
      // 只允许数字和小数点
      let newValue = value.replace(/[^\d.]/g, '')

      // 不能以0开头（除了0.xx的情况）
      if (newValue.length > 1 && newValue[0] === '0' && newValue[1] !== '.') {
        newValue = newValue.substring(1)
      }

      // 只能有一个小数点
      const parts = newValue.split('.')
      if (parts.length > 2) {
        newValue = parts[0] + '.' + parts.slice(1).join('')
      }

      // 限制小数点后最多两位
      if (parts.length === 2 && parts[1].length > 2) {
        newValue = parts[0] + '.' + parts[1].substring(0, 2)
      }

      // 更新数据
      if (!row.monthDataMap) {
        this.$set(row, 'monthDataMap', {})
      }
      this.$set(row.monthDataMap, monthKey, newValue)
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-select {
  width: 100%;
}
.option {
  height: auto;
}
.bigbox {
  background-color: #f1f1f1;
  padding: 10px;
  height: 100%;
  .topbox {
    background-color: #fff;
    padding: 20px;
    box-sizing: border-box;
    height: 80px !important;
    width: 100% !important;
  }
  .bodybox {
    background-color: #fff;
    margin-top: 10px;
    padding: 20px 20px 20px 20px;
    height: 90%;
    .titlebox {
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
      .text {
        font-weight: bold;
        font-size: 18px;
      }
      .right {
        align-items: center;
        i {
          margin-left: 10px;
        }
      }
    }
  }
}

::v-deep.el-date-editor {
  .el-range-separator {
    line-height: 22px;
  }
}

button {
  cursor: pointer;
}
</style>
